package model

import (
	"vueBasic/app/admin/filter"
	"vueBasic/extend/conv"
	"vueBasic/global"
)

var BookM = new(bookModel)

type bookModel struct {
	Id         uint   `form:"id" json:"id"`
	Title      string `form:"title" json:"title"` //标题
	Desc       string `form:"desc" json:"desc"`
	Status     int    `form:"status" json:"status"`
	Thumb      string `form:"thumb" json:"thumb"`
	IsHome     int    `form:"is_home" json:"is_home"`
	Sort       int    `form:"sort" json:"sort"`
	AddTime    int64  `form:"add_time" json:"add_time"`
	UpdateTime int64  `form:"update_time" json:"update_time"`
}

func (*bookModel) TableName() string {
	return global.CONF.Database.Db.Prefix + "book"
}

func (*bookModel) GetList(req *filter.BookReq) ([]bookModel, int64, error) {
	var (
		bookList []bookModel
		count    int64
	)
	query := global.DB.Model(&bookModel{})
	if !conv.IsEmpty(req.Title) {
		query = query.Where("title LIKE ?", req.Title)
	}
	if !conv.IsEmpty(req.Status) {
		query = query.Where("status=?", req.Status)
	}
	if !conv.IsEmpty(req.AddTime) {
		query = query.Where("add_time BETWEEN ? AND ?", conv.UnixTime(req.AddTime[0]), conv.UnixTime(req.AddTime[1]))
	}
	if err := query.Limit(req.Limit).Offset((req.Page - 1) * req.Limit).Order("sort ASC").Find(&bookList).Error; err != nil {
		return nil, 0, err
	}
	//获取总条数
	query.Count(&count)
	return bookList, count, nil
}

func (*bookModel) Add(req *filter.BookAddReq) (uint, error) {
	entity := bookModel{}
	entity.Title = req.Title
	entity.Sort = req.Sort
	entity.Desc = req.Desc
	entity.Status = req.Status
	entity.Thumb = req.Thumb
	entity.IsHome = req.IsHome
	entity.AddTime = req.AddTime
	entity.UpdateTime = req.UpdateTime
	if err := global.DB.Create(&entity).Error; err != nil {
		return 0, err
	}
	return entity.Id, nil
}

func (*bookModel) GetBookById(id int) (*bookModel, error) {
	entity := bookModel{}
	if err := global.DB.Where("id=?", id).Limit(1).First(&entity).Error; err != nil {
		return nil, err
	}
	return &entity, nil
}

func (*bookModel) Update(req *filter.BookUpdateReq) (uint, error) {
	entity := bookModel{Id: req.Id}
	global.DB.First(&entity)
	entity.Title = req.Title
	entity.Sort = req.Sort
	entity.Desc = req.Desc
	entity.Status = req.Status
	entity.Thumb = req.Thumb
	entity.IsHome = req.IsHome
	entity.UpdateTime = req.UpdateTime
	if err := global.DB.Save(&entity).Error; err != nil {
		return 0, err
	}
	return entity.Id, nil
}

func (*bookModel) UpdateExt(req map[string]interface{}) error {
	query := global.DB.Model(&bookModel{})
	if err := query.Where("id=?", req["id"]).Updates(req).Error; err != nil {
		return err
	}
	return nil
}

func (*bookModel) Delete(ids []string) (uint, error) {
	query := global.DB.Where("id IN ?", ids)
	err := query.Delete(&bookModel{}).Error
	if err != nil {
		return 0, err
	}
	return 1, nil
}
